#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#     Filename @  get_logger.py
#       Author @  Huoty
#  Create date @  2016-08-26 10:16:34
#  Description @  get logger
# *************************************************************

from __future__ import absolute_import, print_function, division

import os
import sys

def get_logger(name):
    import logging
    from logging.handlers import SMTPHandler

    class CustomFormatter(logging.Formatter):
        def format(self, record):
            record.host = __import__("socket").gethostname()
            return super(CustomFormatter, self).format(record)

    class CustomSMTPHandler(SMTPHandler):
        def emit(self, record):
            # add extra record
            record.host = __import__("socket").gethostname()
            super(CustomSMTPHandler, self).emit(record)

        def getSubject(self, record):
            formatter = logging.Formatter(fmt=self.subject)
            return formatter.format(record)

    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    # add main log handler for error
    mail_handler = CustomSMTPHandler(
            mailhost = 'smtp.yeah.net',
            fromaddr = os.environ["MAIL_ADDR"],
            toaddrs  = ('loveqing2013@foxmail.com',),
            subject  = '%(name)s Error: %(message)s',
            credentials = (os.environ["MAIL_ADDR"], os.environ["MAIL_PASS"]))
    mail_handler.setLevel(logging.ERROR)
    # mail_handler.setFormatter(CustomFormatter('''\
    mail_handler.setFormatter(logging.Formatter('''\
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Host:               %(host)s
Time:               %(asctime)s

Message:

%(message)s
    '''))
    logger.addHandler(mail_handler)

    # add stream log handler for info
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.INFO)
    stdout_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]'
    ))
    logger.addHandler(stdout_handler)

    return logger

log = get_logger("Log Test")

# Script starts from here

if __name__ == "__main__":
    log.info("hello")
    log.warn("hello")
    log.error("hello")
    log.exception("hello")
    #try:
        #1/0
    #except:
        #log.exception("hello")
